<?php
class ModLog {

    public static function getLink($server='192.168.1.10', $dbName='',$port){
        $logServer = PubServer::getLogServerByDevId($server);
        if(empty($logServer)){
            return false;
        }

        $username = Yii::app()->params['ModLog']['username'];
        $password = Yii::app()->params['ModLog']['password'];
        $config = array(
        		'dsn'       =>  'mysql:host='.$logServer.';port='.$port,
        		'username' =>  $username,
        		'password' =>  $password,
        );
        
        return new PubDbLink($config, $dbName);
    }

    public static function getTblColumns($type){
        $tableInfo = self::getTblInfo();
        $sql = "show columns from ". $tableInfo[$type]['tbl'];

        $dbName = 'mangologdb_desc';

        $dbLink = new PubDbLink('dbLog', $dbName);

        if(!$dbLink){
            return array();
        }

        $list = $dbLink->query($sql);

        return $list;
    }

    public static function getRole($roleIds){
        return array();
//        if(empty($roleIds)){
//            return array();
//        }
//        $dbName = 'romatlogdb';
//        $dbLink = new PubDbLink('dbLog', $dbName);
//        return $dbLink->query('select roleid,rolename,server FROM vewlog_role WHERE roleid IN (:role)', array('role' => $roleIds));
    }

    public static function getLog($type, $params, $cnt=false, $export=false){
        $tblInfo = self::getTblInfo()[$type];
        $fields = "*";
        $serverColumn   = (isset($tblInfo['serverColumn'])) ? $tblInfo['serverColumn'] : 'server';
        $roleColumn     = (isset($tblInfo['roleColumn'])) ? $tblInfo['roleColumn'] : 'roleid';

        $getType        = (isset($tblInfo['type'])) ? $tblInfo['type'] : 'log';

        $where  = " WHERE ctime BETWEEN :begin AND :end ";
        if(strlen($params['time']) == 35){  //排行日志时间选择为到分的时候使用
        	$time_array = explode('~', $params['time']);
        	$time_array[0] = strtr($time_array[0],'.','-');
        	$time_array[1] = strtr($time_array[1],'.','-');
        	$args   = array(
        			'begin' => strtotime($time_array[0]),
        			'end'   => strtotime($time_array[1])
        	);
        	$params['time_start'] = $time_array[0];
        	$params['time_end'] = $time_array[1];
        }else{
        	$args   = array(
        			'begin' => strtotime($params['time_start'] . ' 00:00:00'),
        			'end'   => strtotime($params['time_end'] . ' 23:59:59')
        	);
        }
//        if($type == 'payLogin'){
//            $where .= ' AND TotalRecharge > 0 ';
//        }

        if(!empty($params['server'])){
            $where .= " AND {$serverColumn}=:server ";
            $args['server'] = $params['server'];
            if($type == 'reg'){
            	$args['server'] = 'ALL';
            }
        }

//        if(!empty($params['cid']) || $params['cid'] == '0'){
//            if($params['cid'] != '-1'){
//                $where .= " AND cid=:cid ";
//                $args['cid'] = $params['cid'];
//            }
//        }

        $user = AccAuth::me();
        if($params['os'] != 'ALL' || $user['IsViewAll'] != 1){
        	$where .= " AND platform=:os ";
        	$args['os'] = $params['os'];
        }
        
        

        if(!empty($params['openid'])){
            $where .= " AND openid=:openid ";
            $args['openid'] = $params['openid'];
        }

        if(!empty($params['roleid'])){
            $where .= " AND {$roleColumn}=:roleid ";
            $args['roleid'] = $params['roleid'];
        }

        if(!empty($params['rolename'])){
            $where .= " AND rolename LIKE :rolename ";
            $args['rolename'] = '%' . $params['rolename'] . '%';
        }

        if(isset($params['regchannel'])){
            $where .= " AND cid = :regchannel ";
            $args['regchannel'] = $params['regchannel'];
        }
        
        if(!empty($params['task_id'])){
        	$where .= " AND task_id = :task_id ";
        	$args['task_id'] = $params['task_id'];
        }
        
        if(!empty($params['goods_name'])){
        	$where .= " AND goods_name LIKE :goods_name ";
        	$args['goods_name'] = '%' . $params['goods_name'] . '%';
        }
        
        if(!empty($params['goods_id'])){
        	$where .= " AND goods_id LIKE :goods_id ";
        	$args['goods_id'] = '%' . $params['goods_id'] . '%';
        }
        
        if(!empty($params['currency_type'])){
        	$where .= " AND currency_type = :currency_type ";
        	$args['currency_type'] = $params['currency_type'];
        }
        
        if($type == 'gold' && empty($params['currency_type'])){
        	$currency_type = 14;
        	$where .= " AND currency_type != :currency_type ";
        	$args['currency_type'] = $currency_type;
        }
        
        if(!empty($params['goods_access'])){
        	$where .= " AND goods_access = :goods_access ";
        	$args['goods_access'] = $params['goods_access'];
        }
        
        if(!empty($params['way'])){
        	$where .= " AND way = :way ";
        	$args['way'] = $params['way'];
        }
        
        if(!empty($params['type'])){
        	$where .= " AND type = :type ";
        	$args['type'] = $params['type'];
        }
        
        if(!empty($params['appearance_type'])){
        	$where .= " AND appearance_type = :appearance_type ";
        	$args['appearance_type'] = $params['appearance_type'];
        }
        
        if(!empty($params['inst_type'])){
        	$where .= " AND inst_type = :inst_type ";
        	$args['inst_type'] = $params['inst_type'];
        }
        
        if(!empty($params['map_id'])){
        	$where .= " AND map_id = :map_id ";
        	$args['map_id'] = $params['map_id'];
        }
        
        if(!empty($params['slot'])){
        	$where .= " AND slot = :slot ";
        	$args['slot'] = $params['slot'];
        }
        
        if(!empty($params['suit_type'])){
        	$where .= " AND suit_type = :suit_type ";
        	$args['suit_type'] = $params['suit_type'];
        }
        
        if(!empty($params['item_id'])){
        	$where .= " AND item_id = :item_id ";
        	$args['item_id'] = $params['item_id'];
        }
        
        if(!empty($params['boosid'])){
        	$boosid = $params['boosid'];
        	$where .= " AND bossid = :bossid ";
        	$args['bossid'] = $boosid;
        }
        
        if(!empty($params['mail_title'])){
        	$where .= " AND mail_title LIKE :mail_title ";
        	$args['mail_title'] = '%' . $params['mail_title'] . '%';
        }
        
        if($params['quality'] != ''){
        	$g_ids = self::getGoodIds('quality',$params['quality']);
        	$where .= " AND item_id in ({$g_ids}) ";			
        }
        
        if($params['g_name'] != ''){
        	$g_ids = self::getGoodIds('name',$params['g_name']);
        	$where .= " AND item_id in ({$g_ids}) ";
        }
        
        if($params['stage'] != ''){
        	$g_ids = self::getGoodIds('stage',$params['stage']);
        	$where .= " AND item_id in ({$g_ids}) ";
        }
        
        if($params['star'] != ''){
        	$g_ids = self::getGoodIds('star',$params['star']);
        	$where .= " AND item_id in ({$g_ids}) ";
        }
        
        
        if($params['g_quality'] != ''){
        	$g_ids = self::getGoodIds('quality',$params['g_quality']);
        	$where .= " AND goods_id in ({$g_ids}) ";
        }
        
        if($params['g_g_name'] != ''){
        	$g_ids = self::getGoodIds('name',$params['g_g_name']);
        	$where .= " AND goods_id in ({$g_ids}) ";
        }
        
        if($params['g_stage'] != ''){
        	$g_ids = self::getGoodIds('stage',$params['g_stage']);
        	$where .= " AND goods_id in ({$g_ids}) ";
        }
        
        if($params['g_star'] != ''){
        	$g_ids = self::getGoodIds('star',$params['g_star']);
        	$where .= " AND goods_id in ({$g_ids}) ";
        }
        
        

        $dbLink = self::getLink($params['server'],'',$params['port']);
        
        $dbName = 'mangologdb';

        switch($getType){
            case 'imp':
                $table = $dbName.'.'.$tblInfo['tbl'];
                break;
            case 'log':
            	//查询server的开服日期
            	if(!empty($params['server'])){
            		$modserver = new ModServer();
            		$serverObj = $modserver->findByAttributes(array('develop_id'=>$params['server']));
            		if($serverObj){
            			$open_time = $serverObj->open_time;
            		}
            		 
            		$start = strtotime($params['time_start']);
            		$end = strtotime($params['time_end']);
            		//查询的开始时间小于开服，则用开服时间为起始时间
            		if($open_time != '' && $start < $open_time){
            			$s_open_time = date('Ymd', $open_time);
            			$start = strtotime($s_open_time);
            		}
            		//查询的结束时间大于当前时间，则用当前时间作为截止时间
            		if($end > time()){
            			$s_end_time = date('Ymd His', time());
            			$end = strtotime($s_end_time);
            		}
            	}

                $table  = "(";
                //for($start=strtotime($params['time_start']), $end=strtotime($params['time_end']), $i=31;
                for($i=31;
                    $start<=$end && $i>0; $start+=86400, $i--){                   	
                    $oneDb  = $dbName . '_' . date('Ym', $start);
                    $oneTb  = $tblInfo['tbl'] . '_' . date('Ymd', $start);
                    $table .= " (SELECT * FROM {$oneDb}.{$oneTb} {$where}) UNION ALL";
                    //echo $oneTb;echo '<br/>';
                }
                $table = substr($table, 0, -9);
                $table .= ') AS tbl';
                break;
        }
        
        if($cnt){
            if($getType == 'log') {
                $sql = "select count(1) as cnt from {$table}";
            }else{
                $sql = "select count(1) as cnt from {$table} {$where}";
            }
            $result = $dbLink->query($sql, $args);
            return isset($result[0]['cnt']) ? $result[0]['cnt'] : 0;
        }else{
            $order  = self::getOrder($params['order']);
            if(!$export){
                $limit  = PubFunc::getLimit($params['length'], $params['page']);
            }

            if($getType == 'log'){
                $sql = "SELECT {$fields} FROM {$table} {$order} {$limit}";
            }else{
                $sql = "SELECT {$fields} FROM {$table} {$where} {$order} {$limit}";
            }
            return $dbLink->query($sql, $args);
        }
    }
    
    public static function getGoodIds($filed,$value){
    	$modGoods = new ModGood();
    	$game = PubBase::getCurrentGame();
    	$map = array();
    	$map['g'] = $game;
    	$map[$filed] = $value;
    	$goods_data= $modGoods->select($map);
    	$g_ids = '';
    	foreach ($goods_data as $key=>$val){
    		$g_ids .= ','.$val['g_id'];
    	}
    	$g_ids = substr($g_ids, 1);
    	if($g_ids == ''){
    		$g_ids = 0;
    	}
    	return $g_ids;
    }

    public static function getOrder($order){
        if(PubFunc::checkEmpty($order, array(0, 1))) return '';
        if(!in_array($order[1], array('asc', 'desc'))){
            $sort = 'asc';
        }else{
            $sort = $order[1];
        }
        return " ORDER BY {$order[0]} {$sort} ";
    }

    public static function getTblInfo(){
        return array(
            'reg'           => array('tbl' => 'tbllog_reg'),
            'login'         => array('tbl' => 'tbllog_login'),
            'logout'        => array('tbl' => 'tbllog_logout'),
            'gold'          => array('tbl' => 'tbllog_gold'),
            'goods'         => array('tbl' => 'tbllog_goods'),
            'role'          => array('tbl' => 'tbllog_role'),
            'feedback'      => array('tbl' => 'FeedBackFlow'),
            'fightpve'      => array('tbl' => 'tbllog_pve'),
            'fightpvp'      => array('tbl' => 'tbllog_pvp'),
            'gamebox'       => array('tbl' => 'GemBoxFlow'),
            
            'activityPro'   => array('tbl' => 'PlayerActivityProgressFlow'),
            'pet'           => array('tbl' => 'PetFlow'),
            'petoper'       => array('tbl' => 'PetOperFlow'),
            'activity'      => array('tbl' => 'tbllog_activity'),
            'friend'        => array('tbl' => 'PlayerFriendFlow'),
            'recharge'      => array('tbl' => 'tbllog_recharge', 'type' => 'imp'),
            'shop'          => array('tbl' => 'tbllog_shop'),
            'singing'       => array('tbl' => 'SiningFlow'),
            'online'        => array('tbl' => 'tbllog_online'),// todo
            'level'         => array('tbl' => 'tbllog_levelup'),
            'payLogin'      => array('tbl' => 'PlayerLogin'),
            'equipattr'     => array('tbl' => 'EquipRecreateAttrFlow'),
            'equipskill'    => array('tbl' => 'EquipRecreateSkillFlow'),
            'equipRecattrf' => array('tbl' => 'EquipRecreateExtraAttrFlow'),
            'alarm'         => array('tbl' => 'ItemOpAlarmFlow', 'type' => 'imp'),
            'rolePatrol'    => array('tbl' => 'RolePatrolFlower'),
            'blackMarket'   => array('tbl' => 'BlackMarketShopFlow'),
            'partnerFight'  => array('tbl' => 'PartnerFlightFlow'),
        		
        	
            'achievement'   => array('tbl' => 'tbllog_achievement'),
        	'compose'     => array('tbl' => 'tbllog_compose'),
        	
        	'equipSell' => array('tbl' => 'tbllog_equip_sell'),
        	'equipSwallow' => array('tbl' => 'tbllog_equip_swallow'),
        	'guildCreate' => array('tbl' => 'tbllog_guild_create'),
        	'guildCapital' => array('tbl' => 'tbllog_guild_capital'),
        	'guildLevelup' => array('tbl' => 'tbllog_guild_levelup'),
        	'guildMember' => array('tbl' => 'tbllog_guild_member'),
        	'guildRedpacket' => array('tbl' => 'tbllog_guild_redpacket'),
        		
	        'email'	        => array('tbl' => 'tbllog_mail'),
        	'bossFall'	    => array('tbl' => 'tbllog_boss_fall'),
        	'pickup'	    => array('tbl' => 'tbllog_boss_pickup'),
        	'bossDeath'     => array('tbl' => 'tbllog_boss_death'),
        	'equWear'	    => array('tbl' => 'tbllog_equ_wear'),
        	'equSuit'	    => array('tbl' => 'tbllog_equ_suit'),
        	        	
        	'soulUpgrade'	    => array('tbl' => 'tbllog_soul_upgrade'),
        	'stateUpgrade'	    => array('tbl' => 'tbllog_state_upgrade'),
        	'fashionUpgrade'	    => array('tbl' => 'tbllog_fashion_upgrade'),
        	'swordUpgrade'	    => array('tbl' => 'tbllog_sword_upgrade'),
        		
        	'daily'	    => array('tbl' => 'tbllog_daily'),
        	'sports'	    => array('tbl' => 'tbllog_sports'),
        		
        	'factionMember'	    => array('tbl' => 'tbllog_faction_member'),
        	'factionGrade'	    => array('tbl' => 'tbllog_faction_grade'),
        	'factionCapital'	    => array('tbl' => 'tbllog_faction_capital'),
        	'factionRedpacket'	    => array('tbl' => 'tbllog_faction_redpacket'),
        		
        	'surfaceWing'	    => array('tbl' => 'tbllog_surface_wing'),
        	'unrealWing'	    => array('tbl' => 'tbllog_unreal_wing'),
        	'surfaceMounts'	    => array('tbl' => 'tbllog_surface_mounts'),
        	'unrealMounts'	    => array('tbl' => 'tbllog_unreal_mounts'),
        		
        	'task'	    => array('tbl' => 'tbllog_task'),
        	'orders'	    => array('tbl' => 'tbllog_orders'),
        	'sendcoin'	    => array('tbl' => 'tbllog_sendcoin'),
        	'instEnter'	    => array('tbl' => 'tbllog_inst_enter'),
        	'instExit'	    => array('tbl' => 'tbllog_inst_exit'),
        		
        	'slotStrengthen'	    => array('tbl' => 'tbllog_slot_strengthen'),
        	'equipWear'	    => array('tbl' => 'tbllog_equip_wear'),
        	'equipInlay'	    => array('tbl' => 'tbllog_equip_inlay'),
        	'equipSuit'	    => array('tbl' => 'tbllog_equip_suit'),
        	'rank'	    => array('tbl' => 'tbllog_rank'),
        	'runeUpgrade'	    => array('tbl' => 'tbllog_rune_upgrade'),
        	'giftUse'	    => array('tbl' => 'tbllog_gift_use'),
        		
        	'appearanceUpgrade' => array('tbl' => 'tbllog_appearance_upgrade'),
        	'shapeOpen' => array('tbl' => 'tbllog_shape_open'),
        	'shapeUpgrade' => array('tbl' => 'tbllog_shape_upgrade'),
        	'shapeDecompose' => array('tbl' => 'tbllog_shape_decompose'),
        	'market'=>array('tbl' => 'tbllog_market'),
        );
    }
} 
